﻿using SIMS.Shared.Models;
using SIMS.SqlSugarWebApi.Models;
using SIMS.SqlSugarWebApi.ServiceInterface;
using SqlSugar;

namespace SIMS.SqlSugarWebApi.Services
{
    public class ScoreService : BaseService<Score>, IScoreService
    {
        private DataContext _context;

        public ScoreService(DataContext context) : base(context)
        {
            _context = context;
        }

        public async Task<PagingModel<Score>> GetScores(string studentName, string courseName, int pageNum, int pageSize)
        {
            ISugarQueryable<Score> scores;
            if (!string.IsNullOrEmpty(studentName) && !string.IsNullOrEmpty(courseName))
            {
                var studentIds = _context.db.Queryable<Student>()
                         .Where(r => r.Name.Contains(studentName))
                         .Select(r => r.Id)
                         .ToList();

                var courseIds = _context.db.Queryable<Course>()
                                   .Where(r => r.Name.Contains(courseName))
                                   .Select(r => r.Id)
                                   .ToList();

                scores = _context.db.Queryable<Score>()
                              .In(r => r.StudentId, studentIds)
                              .In(r => r.CourseId, courseIds);
                               
            }
            else if (!string.IsNullOrEmpty(studentName))
            {
                var studentIds = _context.db.Queryable<Student>()
                         .Where(r => r.Name.Contains(studentName))
                         .Select(r => r.Id)
                         .ToList();

                scores = _context.db.Queryable<Score>()
                               .In(r => r.StudentId, studentIds);
            }
            else if (!string.IsNullOrEmpty(courseName))
            {
                var courseIds = _context.db.Queryable<Course>()
                                   .Where(r => r.Name.Contains(courseName))
                                   .Select(r => r.Id)
                                   .ToList();

                scores = _context.db.Queryable<Score>()
                              .In(r => r.CourseId, courseIds);
            }
            else
            {
                scores = _context.db.Queryable<Score>().OrderBy(r => r.Id);
            }
            int count = await scores.CountAsync();
            List<Score> items;
            if (pageSize > 0)
            {
                items = await scores.ToPageListAsync(pageNum, pageSize);
            }
            else
            {
                items = await scores.ToListAsync();
            }
            return new PagingModel<Score>()
            {
                Count = count,
                Items = items
            };
        }
    }
}
